package com.woniuxy.util;

import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.TimeUnit;

public class EnhancedSnowFlake {
    private final long datacenterId;    // 数据中心 ID（可配置）
    private long workerId;              // 机器 ID（动态分配）
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    private static final long START_STMP = 1480166465631L;
    private static final long SEQUENCE_BITS = 12L;
    private static final long WORKER_BITS = 5L;
    private static final long DATACENTER_BITS = 5L;
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_BITS);
    private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_BITS);
    private static final long WORKER_SHIFT = SEQUENCE_BITS;
    private static final long DATACENTER_SHIFT = SEQUENCE_BITS + WORKER_BITS;
    private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_BITS + DATACENTER_BITS;

    private final RedisTemplate<String, Long> redisTemplate;
    private static final String WORKER_ID_KEY = "snowflake:worker:id";

    public EnhancedSnowFlake(long datacenterId, RedisTemplate<String, Long> redisTemplate) {
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException("Datacenter ID 超出范围");
        }
        this.datacenterId = datacenterId;
        this.redisTemplate = redisTemplate;
        this.workerId = allocateWorkerId(); // 动态分配 workerId
    }

    /**
     * 从 Redis 分配 workerId（避免冲突）
     */
    private long allocateWorkerId() {
        Long workerId = redisTemplate.opsForValue().increment(WORKER_ID_KEY, 1);
        if (workerId == null) {
            throw new RuntimeException("无法从 Redis 分配 workerId");
        }
        redisTemplate.expire(WORKER_ID_KEY, 30, TimeUnit.DAYS); // 设置过期时间
        return workerId % (MAX_WORKER_ID + 1); // 确保不越界
    }

    public synchronized long nextId() {
        long timestamp = timeGen();

        // 处理时钟回拨
        if (timestamp < lastTimestamp) {
            long offset = lastTimestamp - timestamp;
            if (offset <= 5) {
                // 轻微回拨，等待追平
                try {
                    Thread.sleep(offset);
                    timestamp = timeGen();
                } catch (InterruptedException e) {
                    throw new RuntimeException("时钟回拨等待中断", e);
                }
            } else {
                // 严重回拨，告警并抛异常
                throw new RuntimeException("时钟回拨超过 5ms，拒绝生成 ID");
            }
        }

        // 同一毫秒内序列号自增
        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & ((1 << SEQUENCE_BITS) - 1);
            if (sequence == 0) {
                // 当前毫秒序列号用尽，等待下一毫秒
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        // 组合 ID
        return ((timestamp - START_STMP) << TIMESTAMP_SHIFT)
                | (datacenterId << DATACENTER_SHIFT)
                | (workerId << WORKER_SHIFT)
                | sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }
}